package com.example.crud.controllers;

import com.example.crud.entities.Book;
import com.example.crud.repositories.BookRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BooksController {

    @Autowired
    private BookRepository repository;

    @GetMapping
    public List<Book> index() {
        return repository.findAll();
    }

    @GetMapping("/{id}")
    public Book show(@PathVariable Long id) {
        return repository.findById(id).get();
    }

    @PostMapping
    public Book create(@RequestBody Book book) {
        return repository.save(book);
    }

    @PatchMapping("/{id}")
    public void update(@PathVariable Long id, @RequestBody Book book) {
        Book bookFromDb = repository.findById(id).get();
        BeanUtils.copyProperties(book, bookFromDb, "id");
        repository.save(bookFromDb);
    }

    @DeleteMapping("/{id}")
    public void destroy(@PathVariable Long id) {
        Book bookFromDb = repository.findById(id).get();
        repository.delete(bookFromDb);
    }
}
